/*
 * @Description: File Description
 * @Author: xiaoan.chen@bshg.com
 * @version: H3.0
 * @Date: 2023-03-20 14:01:07
 * @LastEditTime: 2023-03-28 17:09:59
 */
import { defineStore } from 'pinia'
import type { ApplianceData } from '@/types/appliance'
import { getHomeAppliances } from '@/api/appliance'
import { handleStatus } from '@/handle/appliance'
import { dataRangeConfigGlobalApplianceInfo } from '@/dataReport/dataReportUtil'

export type State = {
  list: ApplianceData[]
  currentHaId: string
  currentHaType: string
}
export type Getters = {
  current(state: State): ApplianceData | null
  currentType(state: State): ApplianceData[] | []
}
export type Actions = {
  loadList(isHandle: boolean): Promise<void>
  setCurrent(current: ApplianceData | string | null): void
  setCurrentType(current: ApplianceData | string | null): void
  updateCurrentName(newName: string): void
}

export const useApplianceStore = defineStore<'appliance', State, Getters, Actions>('appliance', {
  state: () => ({
    list: [],
    currentHaId: '',
    currentHaType: '',
  }),
  getters: {
    current: ({ list, currentHaId }) => list.find((appliance) => appliance.haId === currentHaId) || null,
    currentType: ({ list, currentHaType }) => list.filter((appliance) => appliance.type === currentHaType) || [],
  },
  actions: {
    async loadList(isHandle) {
      return new Promise(async (resolve, reject) => {
        // 存在缓存数据 不再loading
        if (this.list.length !== 0) resolve()

        try {
          const res = await getHomeAppliances()
          let applianceList: ApplianceData[] = res.data || []
          if (isHandle) {
            const statusTasks = applianceList.map((appliance) => handleStatus(appliance))
            applianceList = await Promise.all(statusTasks)
          }
          this.list = applianceList

          if (!this.currentHaId) {
            this.setCurrent(this.list[0])
          }
          resolve()
        } catch (e) {
          console.error(e)
          reject(e)
        }
      })
    },
    setCurrent(current) {
      if (typeof current === 'string') {
        this.currentHaId = current
      } else {
        this.currentHaId = current?.haId || ''
      }
      // 配置全局家电属性
      dataRangeConfigGlobalApplianceInfo()
    },
    setCurrentType(current) {
      if (typeof current === 'string') {
        this.currentHaType = current
      } else {
        this.currentHaType = current?.type || ''
      }
    },
    updateCurrentName(newName: string) {
      if (this.current) this.current.name = newName
    },
  },
})
